package net.maku.generator.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import net.maku.generator.common.page.PageResult;
import net.maku.generator.common.utils.Result;
import net.maku.generator.domain.entity.TemplateEntity;
import net.maku.generator.domain.entity.TemplateGroupEntity;
import net.maku.generator.domain.query.Query;
import net.maku.generator.enums.TemplateGroupTypeEnum;
import net.maku.generator.service.TemplateGroupService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 模板组管理
 */
@RestController
@RequestMapping("maku-generator/gen/template-group")
@AllArgsConstructor
public class TemplateGroupController {

    private TemplateGroupService templateGroupService;

    /**
     * 分页
     *
     * @param query 查询参数
     */
    @GetMapping("page")
    public Result<PageResult<TemplateGroupEntity>> page(Query query) {
        PageResult<TemplateGroupEntity> page = templateGroupService.page(query);
        return Result.ok(page);
    }

    /**
     * 获取模板组信息
     *
     * @param id 模板组ID
     */
    @GetMapping("{id}")
    public Result<TemplateGroupEntity> get(@PathVariable("id") Long id) {
        TemplateGroupEntity templateGroup = templateGroupService.getById(id);
        return Result.ok(templateGroup);
    }

    /**
     * 获取模板组列表
     */
    @GetMapping("list")
    public Result<List<TemplateGroupEntity>> list(@RequestParam(value = "groupName", required = false) String groupName,
                                                  @RequestParam(value = "type", required = false) Integer typeCode) {
        TemplateGroupTypeEnum type = EnumUtil.getBy(TemplateGroupTypeEnum::getCode, typeCode);
        return Result.ok(templateGroupService.list(groupName, type));
    }

    /**
     * 新增模板组
     */
    @PostMapping("add")
    public Result<String> add(@RequestBody TemplateGroupEntity templateGroup) {
        templateGroupService.saveData(templateGroup);
        return Result.ok();
    }

    /**
     * 修改模板组
     */
    @PutMapping("update")
    public Result<String> update(@RequestBody TemplateGroupEntity templateGroup) {
        templateGroupService.updateDataById(templateGroup);
        return Result.ok();
    }

    /**
     * 删除模板组
     */
    @DeleteMapping("delete")
    public Result<Void> delete(@RequestBody List<Long> idList) {
        templateGroupService.deleteData(idList);
        return Result.ok();
    }

    /**
     * 复制模板组
     */
    @PostMapping("/copy")
    public Result<Void> copy(@RequestBody TemplateGroupEntity templateGroup) {
        templateGroupService.copy(templateGroup);
        return Result.ok();
    }

    /**
     * 导入模板组
     */
    @PostMapping("/import")
    public Result<Void> importTemplateGroup(@RequestParam("file") MultipartFile file) throws Exception {
        templateGroupService.importTemplateGroup(file);
        return Result.ok();
    }


    /**
     * 导出模板组
     */
    @GetMapping("export")
    public void export(@RequestParam("idList") List<Long> idList, HttpServletResponse response) throws IOException {
        List<TemplateGroupEntity> list = new ArrayList<>();
        for (Long id : idList) {
            TemplateGroupEntity templateGroup = templateGroupService.getById(id);
            templateGroup.setId(null);
            templateGroup.setCreateTime(null);
            List<TemplateEntity> templateList = templateGroup.getTemplateList();
            if (CollUtil.isNotEmpty(templateList)) {
                for (TemplateEntity template : templateList) {
                    template.setId(null);
                    template.setTemplateGroupId(null);
                    template.setCreateTime(null);
                }
            }
            list.add(templateGroup);
        }
        String jsonStr = JSONUtil.toJsonStr(list);

        //写入到响应流中
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=templateGroup.json");
        response.setHeader("Content-Length", String.valueOf(jsonStr.getBytes().length));
        response.setContentType("application/octet-stream; charset=UTF-");
        IoUtil.write(response.getOutputStream(), false, jsonStr.getBytes());
    }

}
